package com.doubao.user.client;

import com.doubao.user.security.UserContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Feign请求拦截器，添加必要的认证头
 */
@Component
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    
    @Override
    public void apply(RequestTemplate template) {
        log.debug("FeignRequestInterceptor applying headers...");
        try {
            // 尝试从UserContext获取用户ID并添加到请求头
            Long userId = UserContext.getUserId();
            String token = UserContext.getToken(); // 获取token

            if (userId != null) {
                template.header("X-User-ID", userId.toString());
                log.debug("FeignRequestInterceptor: Added X-User-ID header: {}", userId);
            } else {
                log.warn("FeignRequestInterceptor: userId is null, cannot add X-User-ID header.");
            }

            // 恢复添加Authorization头的逻辑
            if (token != null && !token.isEmpty()) {
                template.header("Authorization", "Bearer " + token);
                log.debug("FeignRequestInterceptor: Added Authorization header with token");
            } else {
                log.warn("FeignRequestInterceptor: token is null or empty, cannot add Authorization header.");
            }
        } catch (Exception e) {
            log.error("FeignRequestInterceptor: Failed to add headers", e);
        }
    }
} 